package com.dominator.shiro;

import com.dominator.utils.api.ApiUtils;
import com.dominator.utils.dao.RedisUtil;
import org.apache.shiro.web.filter.authc.AnonymousFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author gsh
 */
public class BackendFilter extends AnonymousFilter {

    private static Logger log = LoggerFactory.getLogger(BackendFilter.class);

    private static RedisUtil ru = RedisUtil.getRu();

    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) {
        ApiUtils.checkFixTime(response);
        return authfilter(request);
    }


    public boolean authfilter(ServletRequest request) {
        HttpServletRequest req = (HttpServletRequest) request;
        try {
            req.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String reqUrl = req.getRequestURI();
        // 是否忽略
        boolean res = ignoreUrl(reqUrl);

//        if (!res) {
//            Dto dto = JsonUtils.toDto((String) req.getParameter("paramStr"));
//            log.info("dto:{}", dto);
//            //checktoken
//            ApiUtils.checkToken(dto.getString("user_name"),dto.getString("token"),ApiUtils.isEmail(dto.getString("user_name"))?"1":"2");
//
//        }


        return true;
    }


    /**
     * 忽略url
     *
     * @param url
     * @return
     */
    private boolean ignoreUrl(String url) {
        // 验证规则
        String[] regEx = {".*login.*",
                ".*upload.*",
                ".*download.*",
                ".*export.*"};
        // 编译正则表达式
        Pattern pattern = null;
        boolean flag = false;
        for (String reg : regEx) {
            pattern = Pattern.compile(reg);

            // 忽略大小写的写法
            Matcher matcher = pattern.matcher(url);
            if (!matcher.matches()) {
                flag = true;
                break;

            }
        }
        // 字符串是否与正则表达式相匹配
        return flag;
    }


}
